
//购物车相关

let car=JSON.parse( localStorage.getItem("car") || "[]")
let store = {
  state:{
    car
  },
  mutations:{
    //加入购物车
    setCar(state,obj){
      let flag = state.car.some((item,index)=>{
        if(item.id==obj.id){
          state.car[index].num= parseInt(obj.num) + parseInt(state.car[index].num)
          return true
        }
      })
      if(!flag){
        state.car.push(obj)
      }
      console.log(state.car)
      localStorage.setItem("car",JSON.stringify(state.car))
    },
    //改变商品数量
    updateCarnum(state,obj){
      state.car.some((item,index)=>{
        if(item.id==obj.id){
          state.car[index].num=parseInt(obj.num)
          return true
        }
      })
      localStorage.setItem("car",JSON.stringify(state.car))
    },
    // 删除商品
    delShop(state,id){
      state.car.some((item,index)=>{
        console.log(item.id==id)
        if(item.id==id){
          state.car.splice(index,1)
          return true
        }
      })
      localStorage.setItem("car",JSON.stringify(state.car))
    }
  },

  getters:{
    //获取购物车商品总数量
    getCarNum(state){
      let count=0
      state.car.forEach(item => {
        if(item.slected){
          count+=parseInt(item.num)
        }
      });
      return count
    },
    getAllPrice(state){
      let price=0
      state.car.forEach(item => {
        if(item.slected){
          price+=parseInt(item.price)*parseInt(item.num)
        }
      });
      return price
    }
  }
}
export default store
